package org.framework.common.cui;

import java.io.File;
import java.io.FileNotFoundException;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.framework.common.api.entity.CommonFile;
import org.framework.common.api.service.bo.CommonFileBo;
import org.framework.common.api.support.constant.SystemConstants;
import org.framework.common.api.support.model.FileModel;
import org.framework.common.ext.util.file.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;

/**
 * 文件操作控制器
 * <p>描述: </p>
 * <p>Company: Professional</p>
 * @author chanlong(陈龙)
 * @date 2016年5月16日 下午3:34:32
 * @version 1.0.2016
 */
@RestController
public class CommonFileController extends AbstractController {

	@Autowired
	protected CommonFileBo fileBo;
	
	/**
	 * 上传用户头像.
	 * @param dbname
	 * @param request
	 * @return
	 * @throws Exception
	 * @author chanlong(陈龙)
	 * @date 2016年5月16日 下午3:34:44
	 */
	@RequestMapping("/{dbname}/file/avatar")
	public Object avatar(@PathVariable final String dbname, DefaultMultipartHttpServletRequest request) throws Exception {
		try{
			String rndcode = request.getParameter("rndcode");
			String group = request.getParameter("group");
			
			MultipartFile source = request.getFile("__source");
			MultipartFile avatar = request.getFile("__avatar1");
			
			String extension = FilenameUtils.getExtension(source.getOriginalFilename());
			String filename = new StringBuilder(rndcode).append(SystemConstants.SYMBOL_DOT).append(extension).toString();
			String filepath = FileUtil.getUploadPath(dbname, group);
			String fullname = new StringBuilder(filepath).append(filename).toString();
			
			File file = new File(fullname);
			FileUtils.write(file, null);
			
			if(file.exists()){
				avatar.transferTo(file);
			}
			
			String fileurl = new StringBuilder(FileUtil.UPLOAD_URL).append(fullname.replace(FileUtil.UPLOAD_PATH, "")).toString();
			
			return new FileUtil.Result(true,"头像上传成功！","",fileurl);
		}catch(FileNotFoundException e){
			return new FileUtil.Result(false,"头像文件未找到！","","");
		}catch(Exception e){
			return new FileUtil.Result(false,"头像上传失败！","","");
		}
	}
	
	/**
	 * 上传文件.
	 * @param dbname
	 * @param model
	 * @return
	 * @throws Exception
	 * @author chanlong(陈龙)
	 * @date 2016年5月16日 下午3:35:00
	 */
	@RequestMapping("/{dbname}/file/upload")
	public Object upload(@PathVariable final String dbname, @ModelAttribute FileModel model) throws Exception {
		// 参数检查
		if (check(dbname) || check(model)) return error("请求参数有误，请检查数据源或参数绑定源！");
		
		try{
			MultipartFile file = model.getFile();
			
			FileUtil.registContext(file);
			
			Object result = FileUtil.saveFile(FileUtil.getUploadPath(dbname, model.getGroup()), file.getOriginalFilename(), new FileUtil.Callback() {
				@Override
				public Object function(final File file) throws Exception {
					if(model.isNotsaved()){
						// 不保存数据库
						return new CommonFile(model, file);
					}else{
						// 注册数据源
						registerDataSource(dbname);
						
						// 保存数据库
						return fileBo.save(model, file);
					}
				}
			});
			
			return result;
		}catch(Exception e){
			e.printStackTrace();
			return error("文件上传失败！", e);
		}
	}
	
	/**
	 * 获取文件列表.
	 * @param dbname
	 * @param model
	 * @return
	 * @throws Exception
	 * @author chanlong(陈龙)
	 * @date 2016年4月24日 下午1:35:03
	 */
	@RequestMapping("/{dbname}/file/find.json")
	public Object files(@PathVariable final String dbname, @ModelAttribute FileModel model) throws Exception {
		// 参数检查
		if (check(dbname)) return error("请求参数有误，请检查数据源或参数绑定源！");
		
		try{
			// 注册数据源
			registerDataSource(dbname);
			
			return fileBo.files(model.getRecordId());
			
		}catch(Exception e){
			return error("获取文件列表失败！", e);
		}
	}
	
	/**
	 * 删除文件.
	 * @param dbname
	 * @param model
	 * @return
	 * @throws Exception
	 * @author chanlong(陈龙)
	 * @date 2016年4月24日 下午1:35:03
	 */
	@RequestMapping("/{dbname}/file/delete")
	public Object delete(@PathVariable final String dbname) throws Exception {
		// 参数检查
		if (check(dbname)) return error("请求参数有误，请检查数据源或参数绑定源！");
		
		try{
			// 注册数据源
			registerDataSource(dbname);
			
			String ids = request.getParameter("ids");
			
			fileBo.delete(ids);
			
			return success("删除文件成功！");
		}catch(Exception e){
			return error("删除文件失败！", e);
		}
	}
}
